﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace WxApp.Helper
{
    public class WeChatHelper
    {
        const string APPID = "wx95c35787e8515e5e";
        const string APPSECRET = "85fcfd47f37dc5e75cee4b670fadc232";
        // 授权后请求的URL
        const string REDIRECT_URI = "http%3a%2f%2fwx.zhengjinfan.cn%2fapi%2fwechat%2foauth2callback";

        #region 获取access_token,
        /// <summary>
        /// 获取access_token,
        /// </summary>
        /// <returns></returns>
        public static string GetBaseAccessToken()
        {
            // 读取缓存的数据
            var access_token = RedisHelper.StringGet("access_token");
            if (access_token.IsNullOrEmpty)
            {
                string url = $"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={APPID}&secret={APPSECRET}";//你成为开发者后会有一个appID和appSecret  
                string response = HttpHelper.HttpGet(url);
                var atc = JsonConvert.DeserializeObject<AccessTokenModel>(response);    //将json数据转化为对象类型并赋值给list  

                // 添加至缓存
                RedisHelper.StringSet("access_token", atc.access_token, new TimeSpan(atc.expires_in));

                return atc.access_token;//获取JSON里access_token值  
            }

            return access_token.ToString();
        }
        /// <summary>
        /// AccessTokenModel
        /// </summary>
        private class AccessTokenModel
        {
            public string access_token { get; set; }  //属性的名字，必须与json格式字符串中的"key"值一样。
            public long expires_in { get; set; }
        }
        #endregion
        #region 获取网页授权接口调用凭证
        /// <summary>
        /// 获取网页授权接口调用凭证
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public static string GetOpenID(string code)
        {
            var url = $"https://api.weixin.qq.com/sns/oauth2/access_token?appid={APPID}&secret={APPSECRET}&code={code}&grant_type=authorization_code";

            var res = HttpHelper.HttpGet(url);
            var model = JsonConvert.DeserializeObject<WebAccessTokenModel>(res);

            RedisHelper.StringSet("WebAccessTokenModel", res);
            return "<script>location.href='https://www.baidu.com/?openid=" + model.openid + "</script>";
        }
        /// <summary>
        /// WebAccessTokenModel
        /// </summary>
        private class WebAccessTokenModel
        {
            /// <summary>
            /// //此access_token与基础支持的access_token不同
            /// </summary>
            public string access_token { get; set; }
            /// <summary>
            /// access_token接口调用凭证超时时间，单位（秒）
            /// </summary>
            public long expires_in { get; set; }
            /// <summary>
            /// 用户刷新access_token
            /// </summary>
            public string refresh_token { get; set; }
            /// <summary>
            /// 用户OpenID
            /// </summary>
            public string openid { get; set; }
            /// <summary>
            /// 用户授权的作用域，使用逗号（,）分隔
            /// </summary>
            public string scope { get; set; }
        }
        #endregion
    }
}
